<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="广告主id" prop="advertiserId">
              <el-input v-model="queryParams.advertiserId" placeholder="请输入完整广告主id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="备注" prop="remarkMessage">
              <el-input v-model="queryParams.remarkMessage" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['oce:microWechatApp:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oce:microWechatApp:delete']" type="danger" plain :disabled="ids.length === 0" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oce:microWechatApp:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="roleTableRef" border v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="小程序名称" prop="appName" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="备注" prop="remarkMessage" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="原始ID" prop="userName" :show-overflow-tooltip="true" width="200">
          <template #default="{row}">
            <el-text type="danger">
              <span class="cursor-pointer" v-copyText="row.userName">{{ row.userName }}</span>
            </el-text>
          </template>
        </el-table-column>
        <el-table-column label="资产ID" prop="instanceId" :show-overflow-tooltip="true" width="200">
          <template #default="{row}">
            <el-text type="danger">
              <span class="cursor-pointer underline" v-copyText="row.instanceId">{{ row.instanceId }}</span>
            </el-text>
          </template>
        </el-table-column>
        <el-table-column label="广告主id" prop="advertiserId" :show-overflow-tooltip="true" width="200" />
        <el-table-column label="品牌" prop="tagInfo" :show-overflow-tooltip="true" width="200" />
        <el-table-column label="资产类型" prop="tagInfoDesc" :show-overflow-tooltip="true" width="200" />
        <el-table-column label="审核状态" align="center" width="100" prop="auditStatus">
          <template #default="scope">
            {{ findEnum(authStatusOptions, scope.row.auditStatus) }}
          </template>
        </el-table-column>
        <el-table-column label="物料状态" align="center" prop="validStatus">
          <template #default="scope">
            {{ findEnum(openStatusOptions, scope.row.validStatus) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <!-- 详情按钮 -->
            <el-link class="mr-1" type="primary" @click="handleDetail(scope.row)">详情</el-link>
            <!-- 共享按钮 -->
            <el-link class="mr-1" type="primary" @click="handleShare(scope.row)">共享</el-link>
            <!-- 编辑按钮 -->
            <el-link v-hasPermi="['oce:microWechatApp:edit']" class="mr-1" type="primary" @click="handleEdit(scope.row)">编辑</el-link>
            <!-- 复制按钮 -->
            <el-link v-hasPermi="['oce:microWechatApp:add']" class="mr-1" type="primary" @click="handleCopy(scope.row)">复制</el-link>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['oce:microWechatApp:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" append-to-body>
      <el-form ref="accountFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="授权方式">
          <div class="method-box">
            <div v-for="dict in methodOptions" :key="dict.value" :class="['method-box-item', form.status == dict.value ? 'active' : '']">
              <div class="title">{{ dict.title }}</div>
              <div class="label">{{ dict.label }}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item class="method-link" label="使用帮助">
          <div>全角色授权指引</div>
        </el-form-item>
        <img :src="stepImg" class="method-img" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <ShareRange ref="shareRangeRef" :info="shareWechat" />
    <CreatePro ref="CreateProRef" :info="shareWechat" :type="selectedType" />
    <Detail ref="DetailRef" />
  </div>
</template>

<script setup name="Account" lang="ts">
import { listWechatApp } from '@/api/advertisement/wechat';
import { addAccount, delAccount, getAccount, listAccount, updateAccount } from '@/api/advertisement/account';
import { AccountVO, AccountForm, AccountQuery } from '@/api/advertisement/account/types';
import stepImg from '@/assets/images/step.png';
import ShareRange from './components/shareRange.vue';
import CreatePro from './components/createPro.vue';
import Detail from './components/detail.vue';
import useAppStore from "@/store/modules/app";

const appStore = useAppStore();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const accountList = ref<AccountVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const accountFormRef = ref<ElFormInstance>();

const selectedType = ref<'copy' | 'edit' | 'new'>('new');
const authStatusOptions = ref([
  { value: 'AUDITING', label: '审核中' },
  { value: 'AUDIT_ACCEPTED', label: '审核通过' },
  { value: 'AUDIT_REJECTED', label: '审核拒绝' }
]);

const openStatusOptions = ref([
  { value: '0', label: '禁用' },
  { value: '1', label: '启用' }
]);

const methodOptions = ref([
  { value: '0', title: '自主授权', label: '适用于在已知账户部署和密码的情况下自主授权' },
  { value: '1', title: '邀请他人授权', label: '适用于不知道账户部署和密码，需要他人协助完成授权流程的情况' }
]);

const findEnum = (list, value) => {
  return list.find((item) => item.value == value)?.label;
};

const shareWechat = ref<AccountVO>();

const shareRangeRef = ref();
const CreateProRef = ref();
const DetailRef = ref();

const initForm: AccountForm = {
  status: '0'
};

const data = reactive<PageData<AccountForm, AccountQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserId: null,
    advertiserName: '',
    remarkMessage:'',
  },
  rules: {
    status: [{ required: true, message: '授权方式不能为空', trigger: 'blur' }]
  }
});
const { form, queryParams, rules } = toRefs(data);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/**
 * 查询账户列表
 */
const getList = () => {
  loading.value = true;
  listWechatApp(proxy?.addDateRange(queryParams.value, dateRange.value)).then((res) => {
    accountList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
/**删除按钮操作 */
const handleDelete = async (row?: AccountVO) => {
  const accountRecordIds = row?.accountId || ids.value;
  await proxy?.$modal.confirm('是否确认删除账户ID为' + accountRecordIds + '数据项目');
  await delAccount(accountRecordIds);
  getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/account/export',
    {
      ...queryParams.value
    },
    `account_${new Date().getTime()}.xlsx`
  );
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: AccountVO[]) => {
  ids.value = selection.map((item: AccountVO) => item.accountId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 重置新增的表单以及其他数据  */
const reset = () => {
  form.value = { ...initForm };
  accountFormRef.value?.resetFields();
};

/** 授权方式 */
const handleAdd = () => {
  //type='new'
  selectedType.value = 'new';
  reset();
  // dialog.visible = true;
  // dialog.title = '授权方式';
  CreateProRef.value?.show();
};
/** 提交按钮 */
const submitForm = () => {
  const link =
    'https://open.oceanengine.com/audit/oauth.html?app_id=1833348663535772&state=1833348663535772&material_auth=1&redirect_uri=https://api-oceanengine.daishubobo.com/juLiang/account/authCallback';
  open(link);
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
onMounted(() => {
  getList();
});

/**
 * 详情按钮操作
 */
const handleDetail = (row: AccountVO) => {
  // 这里添加查看详情的逻辑，例如跳转到详情页
  DetailRef.value?.show(row);
};

/**
 * 共享按钮操作
 */
const handleShare = (row: AccountVO) => {
  // 这里添加共享的逻辑
  shareWechat.value = row;
  shareRangeRef.value?.show();
};

/**
 * 编辑按钮操作
 */
const handleEdit = (row: AccountVO) => {
  selectedType.value = 'edit';
  shareWechat.value = row;
  // 这里添加编辑的逻辑，例如打开编辑弹窗并填充数据
  CreateProRef.value?.show();
};

/**
 * 复制按钮操作
 */
const handleCopy = (row: AccountVO) => {
  selectedType.value = 'copy';
  shareWechat.value = row;
  // 这里添加复制的逻辑，例如复制关键信息到剪贴板
  CreateProRef.value?.show();
};
</script>

<style lang="scss" scoped>
.method-box {
  display: flex;
  font-size: 12px;
  line-height: normal;

  .method-box-item {
    width: 200px;
    padding: 10px;
    border-radius: 2px;
    border: 1px solid #e6e9ed;
    cursor: pointer;
    &:last-child {
      margin-left: 20px;
    }
    .title {
      font-weight: 700;
    }
    .label {
      margin-top: 10px;
    }
  }
  .active {
    color: #2b81fb;
    border: 1px solid #74b8ff;
    background: #e8f2ff;
  }
}
.method-img {
  width: 100%;
}
.method-link {
  cursor: pointer;
  color: #2b81fb;
}
</style>
